package com.tgit.sso.paltform.central.controller;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import com.tgit.sso.paltform.config.ConfigInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.tgit.sso.core.common.ResponseT;
import com.tgit.sso.core.conf.SsoConf;
import com.tgit.sso.core.conf.SsoException;
import com.tgit.sso.core.conf.SsoUser;
import com.tgit.sso.core.util.EncryptUtil;
import com.tgit.sso.core.util.JedisUtil;
import com.tgit.sso.core.util.SsoLoginHandlerUtils;
import com.tgit.sso.paltform.central.entity.AccountInfo;
import com.tgit.sso.paltform.central.entity.LoginInfo;
import com.tgit.sso.paltform.central.service.UserService;
import com.google.code.kaptcha.impl.DefaultKaptcha;
/**
 * app-token模式登录
 * 接口调用模式
 * @author 范再军
 * 2018年10月9日
 */
@RestController
@RequestMapping("/rest")
public class AppController {
	@Autowired
	UserService userService;
	@Autowired
	DefaultKaptcha captchaProducer;

	/**
	 * 
	 * @param loginInfo
	 * @return
	 */
    @RequestMapping("/login")
    public ResponseT<String> login(@Valid @RequestBody LoginInfo loginInfo, HttpServletRequest request ) {

        String username=loginInfo.getUserName();
        String password=loginInfo.getPassword();
        //校验用户信息
        AccountInfo accountInfo = null;
    	/***************************用户名和密码,验证码初步验证***********************************************/
        accountInfo = userService.findByUsername(username);
        if (accountInfo == null) {
            throw new SsoException(SsoConf.ERRORCODE.USERNAME_PASSWORD.name());
        }
        /*******************************************密码校验*****************************************/
        String dbPassword=accountInfo.getPassword();
        String credentialShaPwd="";
        //1.md5登录，2.sha256登录
        try {
        	//sha-模型支持
			credentialShaPwd =  EncryptUtil.hmacSha256(password,"tgit") ;
		} catch (Exception e) {
			throw new SsoException(SsoConf.ERRORCODE.USERNAME_PASSWORD.name());
		}
        //前端传过来的可能是md5加密的密文
        //encryptedDbPassword对数据库的密码进行再次加密，即两次md5加密
        final String encryptedDbPassword =EncryptUtil.getMd5Str(dbPassword);
        //白名单控制-密文登录
		if(ConfigInfo.WHITE_LIST.contains(SsoConf.getRequestIp(request))) {
		    if (!dbPassword.equals(password)&&!encryptedDbPassword.equals(password)&&!credentialShaPwd.equals(dbPassword)) {
		    	throw new SsoException(SsoConf.ERRORCODE.USERNAME_PASSWORD.name());
            }
		}else {
			//密码匹配md5或者sha,不匹配抛出异常
			if (!dbPassword.equals(password)&&!credentialShaPwd.equals(dbPassword)) {
				throw new SsoException(SsoConf.ERRORCODE.USERNAME_PASSWORD.name());
            }
			//匹配继续往下执行
		}
        
        //登录成功，插入redis
        SsoUser ssoUser = new SsoUser();
        ssoUser.setUserid(accountInfo.getUserId());
        ssoUser.setUsername(accountInfo.getUserName());
        
        //生成token
        String token = UUID.randomUUID().toString();
        //插入到redis
        SsoLoginHandlerUtils.login(token, ssoUser);
        //如果此请求带过来旧的token，可以通过token，清除redis的用户信息
        //获取当前req里的sessionId值,从redis清除掉，为啥要清除，请联系作者qq：1299578272
        String oldToken=SsoLoginHandlerUtils.getByHeaderToken(request);
        if(oldToken!=null && JedisUtil.exists(oldToken)) {
        	JedisUtil.expire(oldToken, 0);
        }
        //返回结果
        return new ResponseT<String>(token);
    }


    /**
     * 无参登出
     * @param request
     * @return
     */
    @RequestMapping("/logout")
    public ResponseT<String> logout(HttpServletRequest request) {
    	String reqHeaderToken=SsoLoginHandlerUtils.getByHeaderToken(request);
        // logout
    	SsoLoginHandlerUtils.logout(reqHeaderToken);
    	return new ResponseT<String>(ResponseT.LOGOUT_CODE, SsoConf.LOGOUT_SUCCESS);
    }

}
